<script setup lang="ts">
import { ref } from 'vue'
import { phoneRule, passwordRule, codeRule } from '@/utils/rules'
import { showSuccessToast, showToast, type CountDownCurrentTime, type FormInstance } from 'vant'
import { getCodeApi, loginApi, loginCodeApi } from '@/services/user'
import { useUserStore } from '@/stores'
import { useRoute, useRouter } from 'vue-router'

// 知识点【router】：setup语法中，router和route必须在顶层作用域定义
// 获取路由实例（用于路由跳转等操作）
const router = useRouter()
// 获取当前路由对象（包含路径、参数等信息）
const route = useRoute()

// 知识点：vue3组合式api里面定义组件名称
defineOptions({
  name: 'loginPage',
})

// 表单
const form = ref({
  phone: '',
  password: '',
  code: '',
})
const isChecked = ref(false)

// 密码登录
const onSubmit = async () => {
  if (!isChecked.value) return showToast('请勾选同意用户协议及隐私条款')

  if (isPwdLogin.value) {
    // 密码登录
    const res = await loginApi(form.value.phone, form.value.password)
    useUserStore().setUser(res.data) // 这里重复调用了两次useUserStore()，也可以优化成一个变量
  } else {
    // 验证码登录
    const res = await loginCodeApi(form.value.phone, form.value.code)
    useUserStore().setUser(res.data)
  }

  showSuccessToast('登录成功')
  if (route.query.redirect) {
    // 登录后打开上次页面（如401时）
    router.replace(route.query.redirect as string)
  } else {
    router.replace('/user')
  }
}

// 短信验证码登录
const isPwdLogin = ref(true)
const time = ref(0)
const loginForm = ref<FormInstance>()

// 倒计时变化
const countDownChange = (currentTime: CountDownCurrentTime) => {
  if (currentTime.seconds === 0) {
    time.value = 0
  }
}
// 发送验证码
const sendCode = async () => {
  // 知识点【vant的表单校验】：看文档方法的时候注意看返回值说明，如果有promise说明是异步的，可以加await
  await loginForm.value?.validate('phone')
  time.value = 10000 //倒计时

  await getCodeApi(form.value.phone, 'login')
  showToast('验证码发送成功')
}

// 密码展示与隐藏
const isShowPwd = ref(false)
</script>

<template>
  <div class="login-page">
    <cp-nav-bar right-text="注册" @click-right="$router.push('/register')"></cp-nav-bar>
    <!-- 头部 -->
    <div class="login-head">
      <h3>{{ isPwdLogin ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;">
        <span @click="isPwdLogin = !isPwdLogin">短信验证码登录</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 表单 -->
    <van-form ref="loginForm" autocomplete="off" @submit="onSubmit">
      <van-field
        name="phone"
        maxlength="11"
        placeholder="请输入手机号"
        v-model="form.phone"
        :rules="phoneRule"
        type="tel"
      ></van-field>
      <van-field
        v-if="isPwdLogin"
        placeholder="请输入密码"
        :rules="passwordRule"
        v-model="form.password"
        :type="isShowPwd ? 'text' : 'password'"
      >
        <!-- 知识点【经验】：切换元素、图标等场景的时候记住下面的写法，而不是用v-if，写两个svg-icon元素 -->
        <template #button>
          <svg-icon
            @click="isShowPwd = !isShowPwd"
            :name="isShowPwd ? 'login-eye-on' : 'login-eye-off'"
          ></svg-icon>
        </template>
      </van-field>
      <van-field
        v-else
        placeholder="请输入验证码"
        :rules="codeRule"
        v-model="form.code"
        type="text"
      >
        <template #button>
          <!-- 倒计时 -->
          <van-count-down v-if="time" :time="time" @change="countDownChange">
            <template #default="timeData">
              <span class="btn-send active">{{ `${timeData.seconds}秒后再次发送` }}</span>
            </template>
          </van-count-down>
          <span v-else class="btn-send" size="small" type="primary" @click="sendCode"
            >发送验证码</span
          >
        </template>
      </van-field>

      <div class="cp-cell">
        <van-checkbox v-model="isChecked">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <!--知识点【vant的使用】： 普通的button不会触发表单提交事件和表单验证，vant表单可以添加native-type="submit"属性让他自动触发事件和表单验证 -->
        <van-button block round type="primary" native-type="submit">登 录</van-button>
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- 底部 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <div class="icon">
        <img src="@/assets/qq.svg" alt="" />
      </div>
    </div>
  </div>

  <!-- 知识点：使用svg的时候，href属性值是一个id选择器，记得用#开头 -->
  <!-- <svg aria-hidden="true">
    <use href="#icon-consult-delete" />
  </svg> -->
  <!-- <svg-icon name="consult-alipay"></svg-icon> -->
</template>

<style lang="scss" scoped>
.login {
  &-page {
    padding-top: 46px;
  }
  &-head {
    display: flex;
    padding: 30px 30px 50px;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
.van-form {
  padding: 0 14px;
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .btn-send {
    color: var(--cp-primary);
    &.active {
      color: rgba(22, 194, 163, 0.5);
    }
  }
}
</style>
